package com.csdj.web;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ajaxJson")
public class MyAjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //响应内容 设置纯文本格式
        resp.setContentType("text/html;charset=utf-8");
        //获取请求参数
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        System.out.println("请求参数:" + name);
        System.out.println("请求参数:" + age);
        //业务层调用

        //响应数据
        PrintWriter writer = resp.getWriter();//写
        //String json = "{\"name\":\"" + name + "\",\"age\":\"" + age + "\"}";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("name", "艾瑞莉娅");
        resultMap.put("age", 18);
        if (Integer.parseInt(age)>18){
            resultMap.put("knife", true);
        }else {
            resultMap.put("knife", false);
        }
        resultMap.put("address", "艾欧尼亚");
        String json = JSON.toJSONString(resultMap);
        writer.write(json);
        writer.close();
    }
}
